from django.db import models

# Create your models here.
##需要安装pygments
from django.db import models
from pygments.lexers import get_all_lexers
from pygments.styles import get_all_styles
##add auth
from pygments.lexers import get_lexer_by_name
from pygments.formatters.html import HtmlFormatter
from pygments import highlight

LEXERS = [item for item in get_all_lexers() if item[1]]
LANGUAGE_CHOICES = sorted([(item[1][0], item[0]) for item in LEXERS])
STYLE_CHOICES = sorted([(item, item) for item in get_all_styles()])


class Snippet(models.Model):
    created = models.DateTimeField(auto_now_add=True)
    title = models.CharField(max_length=100, blank=True, default='')
    code = models.TextField()
    linenos = models.BooleanField(default=False)
    language = models.CharField(choices=LANGUAGE_CHOICES, default='python', max_length=100)
    style = models.CharField(choices=STYLE_CHOICES, default='friendly', max_length=100)

    ## 增加模型的权限用户
    owner = models.ForeignKey('auth.User', related_name='snippets', on_delete=models.CASCADE)
    highlighted = models.TextField()

    class Meta:
        ordering = ['created']

    def save(self, *args, **kwargs):
            """
            使用“pygments”库创建高亮显示的HTML代码段的表示形式。
            """
            lexer = get_lexer_by_name(self.language)
            linenos = 'table' if self.linenos else False
            options = {'title': self.title} if self.title else {}
            formatter = HtmlFormatter(style=self.style, linenos=linenos,
                                      full=True, **options)
            self.highlighted = highlight(self.code, lexer, formatter)
            super().save(*args, **kwargs)


#书籍
class TBook(models.Model):
    created = models.DateTimeField(auto_now_add=True)
    book_name = models.TextField()
    book_code = models.TextField()
    author = models.TextField()
    push_time = models.DateTimeField()

    ## 增加模型的权限用户
    owner = models.ForeignKey('auth.User', related_name='tbooks', on_delete=models.CASCADE)

    class Meta:
        ordering = ['created']


#图书管理员
#http://127.0.0.1:8000/bookmanager/addItem/ 新增
## 更新
#方式一：http://127.0.0.1:8000/bookmanager/deleteItem?id=8
#方式二：http://127.0.0.1:8000/bookmanager/7/updateItem/
## 删除
#方式一：http://127.0.0.1:8000/bookmanager/deleteItem?id=8 删除
#方式二：http://127.0.0.1:8000/bookmanager/8/deleteItem/ 删除

class TBookManager(models.Model):
    created = models.DateTimeField(auto_now_add=True)
    name = models.TextField()
    entry_time = models.DateTimeField()
    gender = models.CharField(choices=[('man','男'),('woman','女')], default='man', max_length=5)

    ## 增加模型的权限用户
    owner = models.ForeignKey('auth.User', related_name='tbookmanager', on_delete=models.CASCADE)

    class Meta:
        ordering = ['created']